#include "dxf.h"

dxf::dxf() {}

dxf::dxf(QString filename)
{
    this->filename = filename;
}

int dxf::file_open()
{
    fp.setFileName(filename);
    fp.open(QIODevice::ReadOnly);
    return 0;
}

void dxf::file_close()
{
    fp.close();
}

// 读取一组数据，包括组码及其后的字符串
int dxf::get_couple_line()
{
    QString id_str;
    int     id_code;

    id_code = get_id_code();
    id_str  = get_id_str();

    // if(2 == id_code && 0 == QString::compare("ENTITIES", id_str))
    // {
    //     return 1;
    // }

    // 一个SECTION
    if (0 == id_code && 0 == QString::compare("SECTION", id_str)) {
        return 1;
    }
    return 0;
}

int dxf::get_id_code()
{
    QByteArray id_code_data;
    QString    id_code_str;
    int        id_code;

    id_code_data = fp.readLine();
    id_code_str  = QString::fromUtf8(id_code_data);
    id_code_str.remove(QRegExp("\\s"));
    id_code = id_code_str.toInt();
    return id_code;
}

QString dxf::get_id_str()
{
    QString id_code_str;

    id_code_str = fp.readLine();
    id_code_str.remove(QRegExp("\\s"));
    return id_code_str;
}

bool dxf::is_section()
{
    if (0 == id_code && 0 == QString::compare("SECTION", id_str))
        return true;
    return false;
}

bool dxf::is_comment()
{
    if (999 == id_code)
        return true;
    return false;
}

// dxf文件解析，主要是顺序扫描dxf文件，逐个提取其中的信息
void dxf::dxf_parser()
{
    file_open();
    while (!fp.atEnd()) {
        id_code = get_id_code();
        if (is_comment())
            ;  // comment deal
        else if (is_section()) {
            id_str = get_id_str();
            if (0 == QString::compare("SECTION", id_str))
                dxf_section_read();
        }
        else {
            // warning
        }
    }
    file_close();
}

bool dxf::is_dxf_end()
{
    return fp.atEnd();
}

bool dxf::dxf_read_couple()
{
    if (is_dxf_end())
        return false;
    id_code = get_id_code();
    id_str  = get_id_str();
    return true;
}

int dxf::dxf_section_read()
{
    id_code = get_id_code();
    if (2 == id_code) {
        while (!fp.atEnd()) {
            id_str = get_id_str();
            if (0 == QString::compare("ENTITIES", id_str))
                ;  // deal entities
        }
    }
    else {
        // warning
    }
    return 0;
}
